package com.oocl.RTRLServer.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.oocl.RTRLServer.util.MyThreadPool;
import com.oocl.constant.LogLevel;
import com.oocl.util.ConsoleLogUtil;
import com.oocl.util.ResourceCloser;

public class RTServer {
	private MyThreadPool pool = null;
	private ServerSocket server=null;
	private boolean isRuuning = true;
	private long start;
	private long end;
	
	/**
	 * 启动服务器
	 */
	public void start(){
		start = System.currentTimeMillis();
		pool = new MyThreadPool();
		try {
			server = new ServerSocket(7777);
			ConsoleLogUtil.log("RTLogin server start success...", LogLevel.INFO);
			while(isRuuning){
				end = System.currentTimeMillis();
				Socket socket = server.accept();
				ConsoleLogUtil.log("A user connected to the server", LogLevel.INFO);
				pool.submit(new ServerThread(socket));
			}
		} catch (IOException e) {
			ConsoleLogUtil.log("RTLogin server start wrong!"+e.getMessage(), LogLevel.ERROR);
			ResourceCloser.release(null, null, null, server);
		}finally {
			ResourceCloser.release(null, null, null, server);
			pool.shutdown();
			ConsoleLogUtil.log("RTLogin server stop success...", LogLevel.INFO);
		}
	}
	
	/**
	 * 关闭服务器
	 */
	public void close(){
		this.isRuuning = true;
	}
	
	public long getRunningTime(){
		return end-start;
	}

	public void setRuuning(boolean isRuuning) {
		this.isRuuning = isRuuning;
	}
}
